package com.zhiyin.seal.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.zhiyin.seal.dao.SystemDao;
import com.zhiyin.seal.entity.AccessTokenEntity;
import com.zhiyin.seal.entity.bo.AccessTokenBo;
import com.zhiyin.seal.entity.bo.SdkDeviceBo;
import com.zhiyin.seal.service.SystemService;
import com.zhiyin.seal.util.BeanUtil;
import com.zhiyin.seal.util.HttpUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

@Service
public class SystemServiceImpl implements SystemService {

    @Autowired
    SystemDao systemDao;

    @Override
    public Boolean updateAccessToken(AccessTokenBo accessTokenBo) {
        AccessTokenEntity accessTokenEntity = BeanUtil.copy(accessTokenBo,AccessTokenEntity.class);
        return systemDao.insertAccessToken(accessTokenEntity) > 0;
    }

    @Override
    public AccessTokenBo getAccessToken(Integer type) {
        AccessTokenEntity accessTokenEntity = systemDao.selectAccessToken(type);
        if(accessTokenEntity != null){
            return BeanUtil.copy(accessTokenEntity,AccessTokenBo.class);
        }

        return null;
    }

    @Override
    public SdkDeviceBo getSdkDevice(String mac) {
        String jsonData = HttpUtil.doGet("https://zhiyinseal.cn/smartsealservice/system/device/single?mac=" + mac);
        JSONObject jsonObject = JSONObject.parseObject(jsonData);
        Boolean success = jsonObject.getBoolean("success");
        if(success){
            jsonObject = jsonObject.getJSONObject("data");
            SdkDeviceBo sdkDeviceBo = new SdkDeviceBo();
            sdkDeviceBo.setSdkId(jsonObject.getLong("sdkId"));
            sdkDeviceBo.setMac(jsonObject.getString("mac"));
            sdkDeviceBo.setAllowReset(jsonObject.getBoolean("allowReset"));

            return sdkDeviceBo;
        }

        return null;
    }

    @Override
    public Integer insertData(String sql) {
        return systemDao.insertDataBySql(sql);
    }

    @Override
    public List<Map<String, Object>> fetchData(String sql) {
        return systemDao.selectDataBySql(sql);
    }

    @Override
    public Integer updateData(String sql) {
        return systemDao.updateDataBySql(sql);
    }

    @Override
    public Integer deleteData(String sql) {
        return systemDao.deleteDataBySql(sql);
    }
}
